package cn.com.zj.rpc.proxy;

import cn.com.zj.rpc.client.MyRpcClient;
import cn.com.zj.rpc.common.RpcRequest;
import cn.com.zj.rpc.common.RpcResponse;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * @ClassName MyRpcProxy
 * @Description 客户端代理类
 * 业务：
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 * @Author ZikZ227412
 * @DATE 2021/12/9 15:58
 * @Version 1.0
 */
public class MyRpcProxy {


    public static Object createProxy(Class serviceClass, MyRpcClient myRpcClient) {
        Object o = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //封装rpcRequest对象
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setRequestId(UUID.randomUUID().toString());
                rpcRequest.setClassName(method.getDeclaringClass().getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setParameters(args);
                //创建MyRpcClient对象
//                MyRpcClient myRpcClient = new MyRpcClient(ip, port);
                try {
                    //发送消息
                    Object message = myRpcClient.send(JSONObject.toJSONString(rpcRequest));
                    RpcResponse rpcResponse = JSONObject.parseObject(message.toString(), RpcResponse.class);
                    if (rpcResponse.getError() != null) {
                        throw new RuntimeException(rpcResponse.getError());
                    }
                    return JSONObject.parseObject(rpcResponse.getResult().toString(), method.getReturnType());
                } catch (Exception e) {
                    throw e;

                } finally {
                    myRpcClient.close();
                }

            }
        });
        return o;
    }
}
